//
//  ScrollImageViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/7/21.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ScrollImageViewController.h"
#import "Header.h"
#import "Masonry.h"
#import "Common.h"
#import "UIImageView+WebCache.h"

@interface ScrollImageViewController ()<UIScrollViewDelegate>
{
    UIScrollView*Scroll;
    UILabel * Number;
    Common * com;
    NSMutableArray * pageNumberArr;
    int number;
}
@end

@implementation ScrollImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    com = [[Common alloc]init];
    
    
    [self creatScroll];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.imageArr = [[NSMutableArray alloc]init];
        self.indexNumber = 0;
    }
    return self;
}


-(void)creatScroll{
    
    
    self.view.backgroundColor =[UIColor blackColor];
    UIButton * backBtn =[UIButton buttonWithType:UIButtonTypeCustom];
//    backBtn.backgroundColor = [UIColor whiteColor];
    [backBtn setImage:[UIImage imageNamed:@"picture_back"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, 50, 50);
    [backBtn addTarget:self action:@selector(pressBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).with.offset(30);
        make.size.mas_equalTo(CGSizeMake(35, 22));
        make.left.mas_equalTo(self.view.mas_left).with.offset(20);
    }];
    
    UIButton * DownBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [DownBtn setBackgroundImage:[UIImage imageNamed:@"product_details_photo_icon_download"] forState:UIControlStateNormal];
    DownBtn.frame = CGRectMake(0, 0, 50, 50);
    [DownBtn addTarget:self action:@selector(DownBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:DownBtn];
    DownBtn.backgroundColor = [UIColor clearColor];
    [DownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).with.offset(30);
        make.size.mas_equalTo(CGSizeMake(35, 35));
        make.right.mas_equalTo(self.view.mas_right).with.offset(-20);
    }];
    
    
    
    pageNumberArr = [[NSMutableArray alloc]init];
    Number = [[UILabel alloc]init];
    for (int i=0; i<self.imageArr.count; i++) {
        NSString* page =[NSString stringWithFormat:@"%d/%lu",i+1,(unsigned long)self.imageArr.count];
        [pageNumberArr  addObject:page];
    }
    
    number = self.indexNumber;
    Number.text = pageNumberArr[number];
    Number.textColor = [UIColor whiteColor];
    Number.font = Font(FontOfSize17);
    
    [self.view addSubview:Number];
    
    
    Scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64,Main_Width,Main_height - 106)];
    Scroll.backgroundColor = [UIColor blackColor];
    Scroll.contentSize = CGSizeMake(Main_Width*self.imageArr.count,Main_height - 106);
    Scroll.contentOffset = CGPointMake(self.indexNumber*Main_Width,0);
    Scroll.bounces = NO;
    Scroll.showsHorizontalScrollIndicator = NO;
    Scroll.showsVerticalScrollIndicator = NO;
    Scroll.pagingEnabled = YES;
    Scroll.delegate = self;
    
   __block CGFloat imgHeight = 0;
  __block  CGFloat imgWidth = 0;
    
    CGFloat scale = (screenHeight - 106) /screenHeight;

    
    for (int i = 0; i<self.imageArr.count; i++) {
        UIImageView * images =[[UIImageView alloc]init];
        
        images.frame = CGRectMake(i*Main_Width, 0, screenWidth   , screenHeight - 106);

        [Scroll addSubview:images];

//       [image sd_setImageWithURL:self.imageArr[i]];
        
        __block UIActivityIndicatorView *activityIndicator;

        NSString * str = [NSString stringWithFormat:@"%@",self.imageArr[i]];
        if ([str rangeOfString:@"http"].location !=NSNotFound) {
            
            [images sd_setImageWithURL:self.imageArr[i] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
                if (!activityIndicator)
                {
                    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
                    activityIndicator.center = images.center;
                    //把更新UI放到主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [images addSubview:activityIndicator];
                    });
                    
                    [activityIndicator startAnimating];
                }
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                imgHeight = image.size.height;
                imgWidth = image.size.width;
                
                if (image.size.width > screenWidth || image.size.height > screenHeight) {
                    
                    images.contentMode = UIViewContentModeScaleAspectFit;
                    
                } else {
                    images.contentMode = UIViewContentModeScaleAspectFill;
                    
                    imgHeight = imgHeight * screenWidth/imgWidth;
                    imgWidth = screenWidth;
                    
                    
                    images.frame = CGRectMake(i*Main_Width, (screenHeight - 106 - imgHeight)/2.0 , imgWidth, imgHeight );
                    
                    
                }
                Number.frame = CGRectMake(0, CGRectGetMaxY(Scroll.frame), screenWidth, 40);
                Number.textAlignment = NSTextAlignmentCenter;
                
                [activityIndicator stopAnimating];
                
            }];

        }else{
            
            images.image = self.imageArr[i];

        }


        
        
    }
        
    [self.view addSubview:Scroll];

//        CGFloat scale = (screenHeight - 106) /screenHeight;
//        
//        NSStringFromCGSize(image.image.size);
//        
//        NSLog(@"~~~~~~~~~~~~~~~%@", NSStringFromCGSize(image.image.size));
//        
//         imgHeight = image.image.size.height;
//         imgWidth = image.image.size.width;
//        
//        if (image.image.size.height >= screenHeight * scale || image.image.size.width >= screenWidth) {
//            
//            image.contentMode = UIViewContentModeScaleAspectFit;
//            
//            if (image.image.size.width > screenWidth  && image.image.size.height <= screenHeight * scale) {
//                            imgWidth = screenWidth;
//                            imgHeight = image.image.size.height * image.image.size.width/screenWidth;
//                
//                        }
//                
//                
//                        if (image.image.size.width <= screenWidth && image.image.size.height > screenHeight * scale) {
//                            imgWidth = image.image.size.width * image.image.size.height/(screenHeight* scale);
//                            imgHeight = screenHeight;
//                
//                        }
//                
//                        if (image.image.size.width <= screenWidth && image.image.size.height <= screenHeight * scale) {
//                            imgWidth = image.image.size.width ;
//                            imgHeight = image.image.size.height;
//                
//                        }
//                        
//                        if (image.image.size.width > screenWidth && image.image.size.height > screenHeight) {
//                            
//                            imgWidth = screenWidth;
//                            imgHeight = image.image.size.height * image.image.size.width/screenWidth;
//                        }
//            
//
//        } else {
//            
//            image.contentMode = UIViewContentModeScaleToFill;
//            imgHeight = imgHeight * screenWidth/imgWidth;
//            imgWidth = screenWidth;
//
//
//        }
//        
//        
////   //
////   //        //
//        
////        image.frame = CGRectMake(i*Main_Width+Main_Width/2.0, (screenHeight - 106 - imgHeight)/2.0, imgWidth, imgHeight);
//        
//        
//        [images mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(Scroll.mas_left).with.offset(i*Main_Width+Main_Width/2.0);
//            make.centerY.equalTo(Scroll.mas_centerY);
//            make.size.mas_equalTo(CGSizeMake(imgWidth, imgHeight));
//            make.size.mas_equalTo(CGSizeMake(screenWidth, screenHeight - 106));
//
//        }];
//
//        
//    }
//    self.automaticallyAdjustsScrollViewInsets =NO;
    
//    Number.frame = CGRectMake(0, CGRectGetMaxY(Scroll.frame), 200, 40);
    
//    [Number mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.view.mas_centerX);
//        make.top.mas_equalTo(Scroll.mas_bottom).with.offset(0*kHeight);
//    }];
    
}



-(void)tapAction{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
-(void)pressBtn{
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
//    [self dismissViewControllerAnimated:YES completion:^{
//    }];
}

-(void)DownBtn{
    
    UIImageView * imageView = [[UIImageView alloc]init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageArr[number]]];
    
    //    [imageView setImageWithURL:[NSURL URLWithString:self.imageArr[number]]];
    
    
//    UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}


- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"呵呵";
    if (!error) {
        message = @"成功保存到相册";
        
        UIImageView * backImage = [com createUIImage:@"保存成功" andDelay:1.5f];
        [self.view addSubview:backImage];
        [backImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.centerY.mas_equalTo(self.view.mas_centerY);
        }];
        
        
        
    }else
    {
        
        message = [error description];
        UIImageView * backImage = [com createUIImage:message andDelay:1.0f];
        [self.view addSubview:backImage];
        [backImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.centerY.mas_equalTo(self.view.mas_centerY);
        }];
        
    }
}
-(UILabel*)createUIlabel:(NSString *)title andFont:(CGFloat)font andColor:(UIColor*)color {
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.textColor = color;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:font];CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    // 名字的H
    CGFloat nameH = size.height;
    // 名字的W
    CGFloat nameW = size.width;
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(font)
    return label;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
    number = point.x / Main_Width;
    
    
    Number.text = pageNumberArr[number];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
